package com.shinhye.elephantsafe.engine;

import java.util.ArrayList;
import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.os.Debug.MemoryInfo;

import com.shinhye.elephantsafe.R;
import com.shinhye.elephantsafe.domain.ProcessInfo;

public class ProcessInfomations {

	public static List<ProcessInfo> getAllProcessInfos(Context context) {
		List<ProcessInfo> list = new ArrayList<ProcessInfo>();
		
		PackageManager pm = context.getPackageManager();
		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningAppProcessInfo> procInfoList = am.getRunningAppProcesses();
		
		for(RunningAppProcessInfo runProcInfo : procInfoList) {
			ProcessInfo procInfo = new ProcessInfo();
			String pacNanme = runProcInfo.processName;
			//5. packname
			procInfo.setPackname(pacNanme);
			
			MemoryInfo[] memoryInfos = am.getProcessMemoryInfo(new int[]{runProcInfo.pid});
			long memsize = memoryInfos[0].getTotalPrivateDirty() * 1024;
			//3. memsize
			procInfo.setMemsize(memsize);
			PackageInfo pacInfo;
			try {
				pacInfo = pm.getPackageInfo(pacNanme, 0);
				ApplicationInfo appInfo = pacInfo.applicationInfo;
				Drawable icon = appInfo.loadIcon(pm);
				//1. icon
				procInfo.setIcon(icon);
				String name = appInfo.loadLabel(pm).toString();
				//2. name
				procInfo.setName(name);
				//4. userTask
				if((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0)
					procInfo.setUserProc(true);
				else 
					procInfo.setUserProc(false);
			} catch (NameNotFoundException e) {
				e.printStackTrace();
				procInfo.setName(pacNanme);
				procInfo.setIcon(context.getResources().getDrawable(R.drawable.ic_system_process));
			}
			list.add(procInfo);
		}
		return list;
	}
}
